package com.zy.openchat.util.share;


import android.annotation.SuppressLint;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.webkit.MimeTypeMap;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.ja.openchat.R;
import com.zy.openchat.App;

import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class ShareDialog extends BaseDialogFragment {

    private TextView shareTitle;
    private RecyclerView shareLv;
    private TextView shareCancel;
    private List<ShareBean> shareBeans = new ArrayList<>();
    private BaseQuickAdapter<ShareBean, BaseViewHolder> sharesAdapter;
    private String mimeType = "text/plain";
    private String filePath = "";
    private String authorities = "";
    private String[] shareFilter;
    private String topTitle = "";
    private String shareContent = "";
    private String shareSubject = "";
    private int requestCode = -1;
    private GoShare.FShareBuilder fShareBuilder;

    private Uri uri = null;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle arguments = getArguments();
        fShareBuilder = (GoShare.FShareBuilder) arguments.getSerializable("fShareBuilder");
        filePath = fShareBuilder.getFilePath();
        authorities = fShareBuilder.getAuthorities();
        shareFilter = fShareBuilder.getShareFilter();
        topTitle = fShareBuilder.getTopTitle();
        shareContent = fShareBuilder.getShareContent();
        shareSubject = fShareBuilder.getShareSubject();
        requestCode = fShareBuilder.getRequestCode();

    }

    public ShareDialog() {
    }

    @Override
    protected int setContentView() {
        return R.layout.f_sharedialog;
    }

    public static ShareDialog newInstance(GoShare.FShareBuilder fShareBuilder) {
        ShareDialog fragment = new ShareDialog();
        Bundle args = new Bundle();
        args.putInt(BaseDialogFragment.FDIALOG_GRAVITY, Gravity.BOTTOM);
        args.putFloat(BaseDialogFragment.FDIALOG_ALPHA, 0.5f);
        args.putSerializable("fShareBuilder", fShareBuilder);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void initView(View view) {
        shareTitle = view.findViewById(R.id.share_title);
        shareLv = view.findViewById(R.id.share_lv);
        shareCancel = view.findViewById(R.id.share_cancel);
        shareTitle.setText(TextUtils.isEmpty(topTitle) ? getString(R.string.share_text) : topTitle);
        shareLv.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false));
        sharesAdapter = new BaseQuickAdapter<ShareBean, BaseViewHolder>(R.layout.share_item, shareBeans) {
            @Override
            protected void convert(@NotNull BaseViewHolder fViewHolder, ShareBean shareBean) {
                fViewHolder.setText(R.id.share_tv, shareBean.getAppName());
                fViewHolder.setImageDrawable(R.id.share_img, shareBean.getIcon());
            }
        };
        shareLv.setAdapter(sharesAdapter);
        sharesAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull @NotNull BaseQuickAdapter<?, ?> adapter, @NonNull @NotNull View view, int position) {
                dismiss();
                ShareBean shareBean = shareBeans.get(position);
                if(COPY_PAGEAGE_NAME.equals(shareBean.getPackageName())){
                    ClipboardManager clipboardManager = (ClipboardManager) getContext().getSystemService(Context.CLIPBOARD_SERVICE);
                    if (clipboardManager != null) {
                        ClipData clipData = ClipData.newPlainText("messageContent", shareContent);
                        clipboardManager.setPrimaryClip(clipData);
                        ToastUtils.showShort("已复制");
                    }
                    return;
                }
                try {
                    Intent intent = getIntent(new ComponentName(shareBean.getPackageName(), shareBean.getClassName()), mimeType, uri);
                    if (requestCode != -1) {
                        getActivity().startActivityForResult(intent, requestCode);
                    } else {
                        getActivity().startActivity(intent);
                    }
                }catch (Exception e){
                    ToastUtils.showShort("跳转错误："+e.getMessage());
                }
            }
        });

        shareCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });
        getShareApp();

    }

    private ShareAsync mShareAsync;

    @SuppressLint("CheckResult")
    private void getShareApp() {

        if (!TextUtils.isEmpty(filePath)) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                uri = FileProvider.getUriForFile(getContext(), authorities, new File(filePath));
            } else {
                uri = Uri.fromFile(new File(filePath));
            }
            mimeType = getMIMEType(uri.getPath());
        }
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType(mimeType);
        mShareAsync = new ShareAsync();
        mShareAsync.execute(getActivity().getPackageManager());
    }

    public String getMIMEType(String filePath) {
        String fileType = getFileType(filePath);
        if (TextUtils.isEmpty(fileType)) {
            return "*/*";
        } else {
            return MimeTypeMap.getSingleton().getMimeTypeFromExtension(fileType);
        }
    }

    public String getFileType(String paramString) {
        String str = "";
        if (TextUtils.isEmpty(paramString)) {
            return str;
        }
        int j = paramString.lastIndexOf("/");
        int i;
        int realI;
        if (j > 0) {
            i = paramString.substring(j + 1).lastIndexOf('.');
            realI = j + 1 + i;
        } else {
            i = paramString.lastIndexOf('.');
            realI = i;
        }
        if (i <= -1) {
            return str;
        }
        return paramString.substring(realI + 1);
    }

    @Override
    public void dismiss() {
        super.dismiss();
        if (mShareAsync != null) {
            mShareAsync.cancel(true);
        }
    }

    private Intent getIntent(ComponentName componentName, String mimeType, Uri uri) {
        Intent shareIntent = new Intent(Intent.ACTION_SEND);
        if (componentName != null) {
            shareIntent.setComponent(componentName);
        }
        shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        shareIntent.setType(mimeType);
        if (uri != null) {
            shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
        }
        shareIntent.putExtra(Intent.EXTRA_TEXT, shareContent);
        shareIntent.putExtra(Intent.EXTRA_SUBJECT, shareSubject);
        return shareIntent;
    }

    public static final String COPY_PAGEAGE_NAME = "copy";

    class ShareAsync extends AsyncTask<PackageManager, Integer, List<ShareBean>> {


        @Override
        protected List<ShareBean> doInBackground(PackageManager... packageManagers) {
            List<ShareBean> needMoveFrontShares = new ArrayList<>();
            List<ShareBean> shareBeans = new ArrayList<>();
            Intent intent = new Intent(Intent.ACTION_SEND);
            intent.setType(mimeType);
            List<ResolveInfo> resolveInfos = packageManagers[0].queryIntentActivities(intent,
                    PackageManager.MATCH_DEFAULT_ONLY);
            if (getActivity() == null || getActivity().getApplication() == null) {
                return shareBeans;
            }
            PackageManager pm = getActivity().getApplication().getPackageManager();
            boolean isFindWx = false;
            for (int i = 0; i < resolveInfos.size(); i++) {
                ResolveInfo resolveInfo = resolveInfos.get(i);

                ActivityInfo activityInfo = resolveInfo.activityInfo;
                ShareBean shareBean = new ShareBean();
                shareBean.setAppName(activityInfo.loadLabel(pm).toString());
                shareBean.setPackageName(activityInfo.packageName);
                shareBean.setClassName(activityInfo.name);
                shareBean.setIcon(activityInfo.loadIcon(pm));
                if("微信".equals(shareBean.getAppName())){
                    isFindWx = true;
                }
                if (shareFilter != null && shareFilter.length > 0) {
                    for (int j = 0; j < shareFilter.length; j++) {
                        if (shareBean.getPackageName().equals(shareFilter[j])) {
                            shareBeans.add(shareBean);
                        }
                    }
                } else {

                    if ("微信".equals(shareBean.getAppName()) || "QQ".equals(shareBean.getAppName())) {
                        needMoveFrontShares.add(shareBean);
                    } else {
                        shareBeans.add(shareBean);
                    }
                }
            }
            if(!isFindWx){
                ShareBean copyBean = new ShareBean();
                copyBean.setIcon(ContextCompat.getDrawable(App.getInstanse(),R.drawable.shape_copy_icon));
                copyBean.setAppName("复制");
                copyBean.setPackageName(COPY_PAGEAGE_NAME);
                needMoveFrontShares.add(0,copyBean);
            }
            if (needMoveFrontShares.size() > 0) {
                shareBeans.addAll(0, needMoveFrontShares);
            }
            return shareBeans;
        }

        @Override
        protected void onPostExecute(List<ShareBean> datas) {
            super.onPostExecute(datas);
            if (getDialog() != null && getDialog().isShowing()) {
                shareBeans.clear();
                shareBeans.addAll(datas);
                sharesAdapter.notifyDataSetChanged();
            }
        }
    }


}
